// order-submit.js
var api = require('../../api.js');
var app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        imgServer :  api.default.img_server,
        total_price: 0,
        address: null,
        express_price: 0.00,
        content: '',
        offline: 0,
        express_price_1: 0.00,
        name: "",
        mobile: "",
        salemanShareCode:null,//经销商优惠码
        moneyIcon:api.MONEYICON,
        moneyIconOther:api.MONEYICONOTHER,
        delivery:'EMS',//EMS || 船运
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      var page = this;
      page.setData({
          options: options,
          store: wx.getStorageSync("store")
      });
    },
    bindkeyinput: function (e) {
      this.setData({
          content: e.detail.value
      });
    },
    KeyName: function (e) {
      this.setData({
          name: e.detail.value
      });
    },
    KeyMobile: function (e) {
      this.setData({
          mobile: e.detail.value
      });
    },
    getOffline: function (e) {
        var express = this.data.express_price;
        var express_1 = this.data.express_price_1;
        var offline = e.target.dataset.index;
        if (offline == 1) {
            this.setData({
                offline: offline,
                express_price: 0,
                express_price_1: express
            });
        } else {
            this.setData({
                offline: offline,
                express_price: express_1
            });
        }
    },
    onDeliveryChange(event){
        this.setData({
            delivery: event.detail,
          });
    },
    orderSubmit: function () {
		var access_token = wx.getStorageSync("access_token");
        var page = this;
        var offline = 0;//快递
        var data = {};
        data.type=3;
		data.userid=access_token;
        if (offline == 0) {
            if (!page.data.address || !page.data.address.id) {
                wx.showToast({
                    title: "请选择收货地址",
                    image: "/images/icon-warning.png",
                });
                return;
            }
            data.addressId = page.data.address.id;
        } else {
            data.address_name = page.data.name;
            data.address_mobile = page.data.mobile;
            if (page.data.shop.id)
                data.shop_id = page.data.shop.id;
        }
        data.offline = offline;
        if (page.data.options.cart_id_list) {
            data.cartIds = page.data.options.cart_id_list.split(",");
           // data.type=2;
        }
        if (page.data.options.goods_info) {
            var info  = JSON.parse(page.data.options.goods_info);
          //  data.type=1;
          let tempArr = [];
          tempArr.push(info.cart_id_list);
            data.cartIds = tempArr;
            if(info.productType){
                data.productType = info.productType
            }
        }
        if (page.data.picker_coupon) {
            data.couponId = page.data.picker_coupon.couponId;
        }
        if (page.data.content) {
            data.content = page.data.content
        }
        wx.showLoading({
            title: "正在提交",
            mask: true,
        });
        data.payType = 2;//0->未支付；1->支付宝；2->微信
        data.depotId = page.data.depotInfo.id;
        data.deliveryStyle = page.data.delivery;
        data.type=2;//都是从购物车过来的
        console.log(data);
        // return;
        //提交订单
        app.request({
            url: api.order.submit,
            method:"post",
            data: data,
            success: function (res) {
                if (res.code == 200) {
                    setTimeout(function () {
                        wx.hideLoading();
                    }, 1000);
                    setTimeout(function () {
                        page.setData({
                            options: {},
                        });
                    }, 1);
                    // wx.redirectTo({
                    //     url: "/pages/order/order?status=1",
                    // });
                     var order_id = res.data.order.id;
                    // var order_sn = res.data.order.orderSn;
                    let realPayAmount = res.data.order.exchangePayAmount;
                    if((!res.data.sdk_params )|| (realPayAmount<=0 && order_id)){//0元支付
                       wx.redirectTo({
                           url: "/pages/order/order?id="+order_id,//订单详情
                       });
                       return;
                    }
                    console.log("第三方调用成功！！！");
                  console.log(res.data.sdk_params);
                  let sdk_params = res.data.sdk_params;
                  if (sdk_params){
                    sdk_params = JSON.parse(sdk_params);
                    // //发起支付
                    wx.requestPayment({
                      timeStamp: sdk_params.timeStamp,
                      nonceStr: sdk_params.nonceStr,
                      package: sdk_params.package,
                      signType: sdk_params.signType,
                      paySign: sdk_params.paySign,
                      success: function (e) {
                        wx.showModal({
                            title: '提示',
                            content: '支付成功~',
                            cancelText:'返回首页',
                            confirmText:'查看订单',
                                success (res) {
                                if (res.confirm) {
                                    wx.redirectTo({
                                        url: "/pages/order/order?id="+order_id,//订单详情
                                    });
                                } else if (res.cancel) {
                                    wx.switchTab({
                                        url:'/pages/index/index',//返回首页
                                    })
                                }
                                }
                            })
                      },
                      fail: function (e) {
                      },
                      complete: function (e) {
                        if (e.errMsg == "requestPayment:fail" || e.errMsg == "requestPayment:fail cancel") {//支付失败转到待支付订单列表
                            if (page.data.options.goods_info) {
                                var info  = JSON.parse(page.data.options.goods_info);
                                if(info.productType==1){//虚拟商品
                                    page.cartDelete();
                                }
                            }
                            
                            wx.showModal({
                            title: "提示",
                            content: "订单尚未支付",
                            showCancel: false,
                            confirmText: "确认",
                            success: function (res) {
                              if (res.confirm) {
                                wx.redirectTo({
                                  url: "/pages/order/order?status=0",//待支付列表
                                });
                              }
                            }
                          });
                          return;
                        }
                        if (e.errMsg == "requestPayment:ok") {
                          return;
                        }
                        wx.redirectTo({
                          url: "/pages/order/order?status=1",
                        });
                      },
                    });
                  }
                   

//return




                    //支付还没调通，先走这个成功的回调//
//                     app.request({
//                       url: api.order.pay_success + order_sn,
//                         //method:"post",
//                         //data: order_id,
//                         // {
//                         //     orderId:order_id
//                         // },
//                         success: function (res) {
                           
//                             if(res.code==200){
//                               wx.showToast({
//                                 title: '支付成功！',
//                               })
//                                 wx.redirectTo({
//                                     url: "/pages/order/order?status=1",
//                                 });
//                             }
//                         }
//                     })

// return;


                    //获取支付数据
                    // app.request({
                    //     url: api.order.pay_data,
                    //     data: {
                    //         id: order_id,
                    //         payType: 2,
                    //     },
                    //     success: function (res) {
                    //         if (res.code == 200) {
                               
                    //             return;
                    //         }else {
                    //             wx.showToast({
                    //                 title: res.message,
                    //                 image: "/images/icon-warning.png",
                    //             });
                    //             return;
                    //         }
                    //     }
                    // });
                }else {
                    wx.hideLoading();
                    wx.showToast({
                        title: res.message,
                        image: "/images/icon-warning.png",
                    });
                    return;
                }

            }
        });
    },
    cartDelete: function () {
        var page = this;
        let id= page.data.options.cart_id_list;
        let deleteIds=[];
        deleteIds.push(id);
        app.request({
            url: api.cart.delete+id,
            success: function (res) {
                console.log("删除成功");              
            }
        });
    },
    redirectReList(){//跳转到凑单列表页
      let self = this;
      let depotId = self.data.depotInfo.id;
      console.log(depotId)
      let transferData = {cart_id_list:this.data.options.cart_id_list};
      wx.navigateTo({
        url: '/pages/recommend-list/recommend-list?depotId=' + depotId,
        events: {
          acceptDataFromOpenedPage(data) {
            console.log(data);
            let tempObj = {};
            tempObj.options={};
            tempObj.options.cart_id_list = data.data;
            tempObj.options.depotId = data.depotId;
            //tempObj.options[cart_id_list] = data.data;
            //self.getOrderData(tempObj)
            // tempObj['options[cart_id_list]'] = data.data;
            self.setData(tempObj);
            console.log(self.data.options)
          }
        },
        success: function (res) {
          res.eventChannel.emit('acceptDataFromOpenerPage', transferData)
        }
      })

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var page = this;
        var address = wx.getStorageSync("picker_address");
        console.log(address);
        if (address) {
            page.setData({
                address: address,
                // name: address.name,
                // mobile: address.mobile
            });
            wx.removeStorageSync("picker_address");
        }
        page.getOrderData(page.data.options);
    },

    getOrderData: function (options) {
        console.log(options)
		var access_token = wx.getStorageSync("access_token");
        var page = this;
        var address_id = 0;
        if (page.data.address && page.data.address.id){
            address_id = page.data.address.id;
        }
        //购物车过来的
        if (options.cart_id_list) {
            console.log(options.cart_id_list);
            var cart_id_list = options.cart_id_list;
            console.log(cart_id_list);
            wx.showLoading({
                title: "正在加载",
                mask: true,
            });
            app.request({
                url: api.order.submit_preview,
               //url: api.order.generateConfirmOrder,
               //method:"post",
                data: 
                // cart_id_list,
                {
                  //cartItemIds:cart_id_list,
				          userid:access_token,
                  cartIds: options.cart_id_list,
                  type:2,
                  addressId: address_id,
                  depotId: page.data.options.depotId,
                  couponId: page.data.picker_coupon ? page.data.picker_coupon.couponId : ""
                }
                ,
                success: function (res) {
                    wx.hideLoading();
                    if (res.code == 200) {
                        if(!page.data.address || Object.keys(page.data.address).length == 0){
                            page.getDefaultAddress();
                        }

                        page.setData({
                            cart_id_list: res.data.cart_id_list,
                           // salemanShareCode:res.data.code,
                            total_price: res.data.total_price,
                            goods_list: res.data.cartPromotionItemList,
                            jifen: res.data.integrationConsumeSetting,
                            address: res.data.address,
                            calcAmount:res.data.calcAmount,
                            //coupon_list: res.data.couponHistoryDetailList.coupon,
                            coupon_list: res.data.couponHistoryDetailList,
                            depotInfo:res.data.depotInfo,//仓库信息
                        });
                        if (res.data.send_type == 1) {//仅快递
                            page.setData({
                                offline: 0,
                            });
                        }
                        if (res.data.send_type == 2) {//仅自提
                            page.setData({
                                offline: 1,
                            });
                        }
                    }
                    if (res.code == 1) {
                        wx.showModal({
                            title: "提示",
                            content: res.message,
                            showCancel: false,
                            confirmText: "返回",
                            success: function (res) {
                                if (res.confirm) {
                                    wx.navigateBack({
                                        delta: 1,
                                    });
                                }
                            }
                        });
                    }
                }
            });
        }
        //商品详情页直接购买过来的
        if (options.goods_info) {
            var info  = JSON.parse(options.goods_info);
            console.log(info);
            wx.showLoading({
                title: "正在加载",
                mask: true,
            });
            let tempdata={
              userid:access_token,
              cartIds:info.cart_id_list,
              type:2,
              count: info.count,
              addressid: address_id,
              depotId: info.depotId,
              couponId: page.data.picker_coupon ? page.data.picker_coupon.couponId:""
            };
            if(info.productType){
                tempdata.productType = info.productType
            }
            app.request({
                url: api.order.submit_preview,
                data: tempdata,
                success: function (res) {
                    wx.hideLoading();
                    if (res.code == 200) {
                        if(!page.data.address || Object.keys(page.data.address).length == 0){
                            page.getDefaultAddress();
                        }

                        page.setData({
                            total_price: res.data.total_price,
                            goods_list: res.data.cartPromotionItemList,
                            jifen: res.data.integrationConsumeSetting,
                            // address: res.data.address,
                            //这里在选择了地址以后返回到当前页的时候，把address字段覆盖了。。。
                            calcAmount:res.data.calcAmount,
                            //coupon_list: res.data.couponHistoryDetailList.coupon,
                            coupon_list: res.data.couponHistoryDetailList,
                            depotInfo:res.data.depotInfo,//仓库信息
                        });
                        if (res.data.send_type == 1) {//仅快递
                            page.setData({
                                offline: 0,
                            });
                        }
                        if (res.data.send_type == 2) {//仅自提
                            page.setData({
                                offline: 1,
                            });
                        }
                    }
                    if (res.code == 1) {
                        wx.showModal({
                            title: "提示",
                            content: res.message,
                            showCancel: false,
                            confirmText: "返回",
                            success: function (res) {
                                if (res.confirm) {
                                    wx.navigateBack({
                                        delta: 1,
                                    });
                                }
                            }
                        });
                    }
                }
            });
        }
    },
    getDefaultAddress(){
        let page = this;
        let access_token = wx.getStorageSync("access_token");
        app.request({
            url: api.user.address_list,
            data: {
                userid:access_token,
				  pageSize:15
            },
            success: function (res) {
                if (res.code == 200) {
                    let result = res.data
                    result.forEach((item)=>{
                        if(item.defaultStatus){
                            page.setData({
                                address: item,
                            });
                        }
                    })
                }
            }
        })
    },

    copyText: function (e) {
        var text = e.currentTarget.dataset.text;
        if (!text)
            return;
        wx.setClipboardData({
            data: text,
            success: function () {
                wx.showToast({
                    title: "已复制内容",
                });
            },
            fail: function () {
                wx.showToast({
                    title: "复制失败",
                    image: "/images/icon-warning.png",
                });
            },
        });
    },

    showCouponPicker: function () {
        var page = this;
        if (page.data.coupon_list && page.data.coupon_list.length > 0) {
            page.setData({
                show_coupon_picker: true,
            });
        }
    },

    pickCoupon: function (e) {
		
        var page = this;
        var index = e.currentTarget.dataset.index;
        if (index == '-1' || index == -1) {
            page.setData({
                picker_coupon: false,
                show_coupon_picker: false,
                'options.couponId':null
            });
           
        } else {
          let params = page.data.options;
          page.setData({
            picker_coupon: page.data.coupon_list[index],
            show_coupon_picker: false,
          });
         
        }
        page.getOrderData(page.data.options);//重新计算价格
    },

    numSub: function (num1, num2, length) {
        return 100;
    },
    showShop: function (e) {
        var page = this;
        if (page.data.shop_list && page.data.shop_list.length > 1) {
            page.setData({
                show_shop: true,
            });
        }
    },
    pickShop: function (e) {
        var page = this;
        var index = e.currentTarget.dataset.index;
        if (index == '-1' || index == -1) {
            page.setData({
                shop: false,
                show_shop: false,
            });
        } else {
            page.setData({
                shop: page.data.shop_list[index],
                show_shop: false,
            });
        }
    }

});